package com.cj.myblog.common.util;

import com.xiaoleilu.hutool.date.DateUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


public class FileUtils {
public static Log logger = LogFactory.getLog(FileUtils.class);


	public static List<String> uploadFile(HttpServletRequest request, String directory) {
		String path = "";
		String[] validExt = {".jpg",".jpeg",".gif",".png",".mp3",".mp4",".zip"};
		Set<String> validSet = new HashSet<String>(Arrays.asList(validExt));

		String root = ClassUtils.getDefaultClassLoader().getResource("").getPath();
		String realPath = root.substring(0,root.length()-8);
		List<String> uploadPath = new ArrayList<>();

		//解析器解析request的上下文
		CommonsMultipartResolver multipartResolver =
				new CommonsMultipartResolver(request.getSession().getServletContext());
		//先判断request中是否包涵multipart类型的数据，
		if (multipartResolver.isMultipart(request)) {
			//再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile((String) iter.next());
				if (file != null) {
					//原文件名
					String fileName = file.getOriginalFilename();
					//获取文件名后缀
					String extName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
					if (validSet.contains(extName)){
						//重命名上传后的文件名,使用时间戳作为文件名称
						fileName = System.currentTimeMillis()+String.valueOf(new Random().nextInt(10000))+extName;
						//上传服务器目录
						path = realPath + "upload"
								+ "/" + directory
								+ "/" + DateUtil.formatDate(new Date());
						File folderFile = new File(path);
						if (!folderFile.exists()){
							folderFile.mkdirs();
						}

						path +="/" + fileName;
						File localFile = new File(path);
						try {
							file.transferTo(localFile);
						} catch (IOException e) {
							logger.error(e.getMessage());
						}
						uploadPath.add(path);
					}

				}
			}
		}
		return uploadPath;
	}


	public static String getZipFileContent(File zipFile, String readFileName) {

		StringBuilder content = new StringBuilder();

		try {
			ZipFile zip = new ZipFile(zipFile);
			Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
			ZipEntry ze;
			// 枚举zip文件内的文件/
			while (entries.hasMoreElements()) {
				ze = entries.nextElement();
				// 读取目标对象
				if (ze.getName().equals(readFileName)) {
					Scanner scanner = new Scanner(zip.getInputStream(ze));
					while (scanner.hasNextLine()) {
						content.append(scanner.nextLine());
					}
					scanner.close();
				}
			}
			zip.close();

		} catch (IOException e) {
			logger.error(e.getMessage());
		}

		return content.toString();
	}

	public static String getJarFileContent(File file, String readFileName) {

		StringBuilder content = new StringBuilder();

		try {
			JarFile jarFile = new JarFile(file);
			Enumeration<JarEntry> entries = (Enumeration<JarEntry>) jarFile.entries();
			JarEntry jar;
			// 枚举zip文件内的文件/
			while (entries.hasMoreElements()) {
				jar = entries.nextElement();
				// 读取目标对象
				if (jar.getName().equals(readFileName)) {
					Scanner scanner = new Scanner(jarFile.getInputStream(jar));
					while (scanner.hasNextLine()) {
						content.append(scanner.nextLine());
					}
					scanner.close();
				}
			}
			jarFile.close();

		} catch (IOException e) {
			logger.error(e.getMessage());
		}

		return content.toString();
	}



	public static void main(String[] args) {
		String path = "/opt/tomcat/webapps/ROOT";
		System.out.println(path.substring(0,path.lastIndexOf("/")));
	}


}
